﻿#region Code File Comment

// SOLUTION   ： redis
// PROJECT    ： Hiram.Redis
// FILENAME   ： utils.cs
// AUTHOR     ： soft-zh
// CREATE TIME： 2016-12-1 9:42
// COPYRIGHT  ： 版权所有 (C) gbat https://gitee.com/gbat 2016~2018

#endregion

#region using namespace

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using NewLife.Serialization;
using Newtonsoft.Json;
using ProtoBuf.Meta;

#endregion

namespace Hiram.Redis
{
    class Utils
    {
        public static byte[] Eof = Encoding.ASCII.GetBytes("\r\n");

        public static string GetString(ArraySegment<byte> data)
        {
            if (data.Count > 0)
                return Encoding.UTF8.GetString(data.Array, data.Offset, data.Count);
            return null;
        }

        public static object GetJson(ArraySegment<byte> data, Type type)
        {
            var value = GetString(data);
            if (string.IsNullOrEmpty(value))
                return null;
            return value;//JsonConvert.DeserializeObject(value,type);
            // var s = new DataContractJsonSerializer(type);        
        }
        public static object GetJson<T>(ArraySegment<byte> data)
        {
            var value = GetString(data);
            if (string.IsNullOrEmpty(value))
                return null;
            return JsonConvert.DeserializeObject(value, typeof(T));

        }
        public static object GetProtobuf(ArraySegment<byte> data, Type type)
        {
            if (data.Count > 0)
            {
                var stream = new MemoryStream(data.Array, data.Offset, data.Count);
                stream.Position = 0;
                return RuntimeTypeModel.Default.Deserialize(stream, null, type);
            }

            return null;
        }
    }
}